<template>
  <el-dialog
    title="选择方案"
    :visible.sync="dialogVisible"
    width="80%"
    :before-close="handleClose"
    class="scheme-selector-dialog"
  >
    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="方案标题">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入方案标题"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleSearch"
          />
        </el-form-item>
        <el-form-item label="赛事分类">
          <el-select
            v-model="searchForm.category"
            placeholder="请选择分类"
            clearable
            style="width: 150px"
          >
            <el-option label="足球" :value="1" />
            <el-option label="篮球" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否付费">
          <el-select
            v-model="searchForm.is_free"
            placeholder="请选择"
            clearable
            style="width: 120px"
          >
            <el-option label="付费" :value="1" />
            <el-option label="不付费" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否不中退">
          <el-select
            v-model="searchForm.no_win_back"
            placeholder="请选择"
            clearable
            style="width: 120px"
          >
            <el-option label="是" :value="1" />
            <el-option label="否" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 方案列表 -->
    <el-table
      ref="schemeTable"
      v-loading="loading"
      :data="schemeList"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="title" label="方案标题" min-width="150">
        <template slot-scope="scope">
          <div class="scheme-info">
            <div class="scheme-title">{{ scope.row.title || '未设置标题' }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="category" label="赛事分类" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.category === 1 ? 'success' : 'warning'">
            {{ scope.row.category === 1 ? '足球' : '篮球' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="expert_info" label="专家" width="120">
        <template slot-scope="scope">
          {{ scope.row.expert_info ? scope.row.expert_info.nickname : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="pass_lx_text" label="过关类型" width="100" />
      <el-table-column prop="show_lx_text" label="显示类型" width="120" />
      <el-table-column prop="price" label="价格" width="100">
        <template slot-scope="scope">
          <span style="color: #e6a23c; font-weight: bold">¥{{ scope.row.price || '0.00' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="is_free" label="是否付费" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_free === 1 ? 'success' : 'info'">
            {{ scope.row.is_free === 1 ? '付费' : '不付费' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="no_win_back" label="是否不中退" width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.no_win_back === 1 ? 'warning' : 'info'">
            {{ scope.row.no_win_back === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '显示' : '隐藏' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="160" />
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="pagination.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 底部操作按钮 -->
    <div slot="footer" class="dialog-footer">
      <div class="selected-info">
        <span v-if="selectedSchemes.length > 0">
          已选择 {{ selectedSchemes.length }} 个方案
        </span>
      </div>
      <div>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :disabled="selectedSchemes.length === 0" @click="handleConfirm">
          确定选择
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { recommendationDatalist } from '../../../libs/api'

export default {
  name: 'SchemeSelector',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    // 是否多选：默认单选，传入 true 开启多选
    multiple: {
      type: Boolean,
      default: false
    },
    // 多选时的上限（可选）
    maxSelected: {
      type: Number,
      default: Infinity
    }
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      schemeList: [],
      selectedSchemes: [],
      searchForm: {
        title: '',
        category: '',
        is_free: '',
        no_win_back: ''
      },
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      searchTimer: null
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val) {
        this.getSchemeList()
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  beforeDestroy() {
    // 清理定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer)
    }
  },
  methods: {
    // 获取方案列表
    getSchemeList() {
      this.loading = true
      const params = {
        ...this.searchForm,
        page: this.pagination.current,
        limit: this.pagination.size,
        sf_pt: 2 // 平台标识
      }

      recommendationDatalist(params).then(res => {
        if (res && res.data) {
          this.schemeList = res.data.list || []
          this.pagination.total = res.data.total || 0
        } else {
          this.schemeList = []
          this.pagination.total = 0
        }
        this.loading = false
      }).catch(() => {
        this.schemeList = []
        this.pagination.total = 0
        this.loading = false
      })
    },

    // 搜索
    handleSearch() {
      // 清除之前的定时器
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
      }
      // 设置防抖，300ms 后执行搜索
      this.searchTimer = setTimeout(() => {
        this.pagination.current = 1
        this.getSchemeList()
      }, 300)
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        title: '',
        category: '',
        is_free: '',
        no_win_back: ''
      }
      this.pagination.current = 1
      this.getSchemeList()
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pagination.size = val
      this.pagination.current = 1
      this.getSchemeList()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.pagination.current = val
      this.getSchemeList()
    },

    // 选择改变
    handleSelectionChange(selection) {
      // 防止在加载过程中处理选择
      if (this.loading) {
        return
      }

      if (!this.multiple) {
        // 单选：仅保留最后一次选择的那一项
        if (selection.length > 1) {
          // 如果选择了多个，只保留最后一个
          const last = selection[selection.length - 1]
          this.$refs.schemeTable.clearSelection()
          this.$nextTick(() => {
            this.$refs.schemeTable.toggleRowSelection(last, true)
            this.selectedSchemes = [last]
          })
        } else {
          this.selectedSchemes = selection
        }
        return
      }
      // 多选：尊重上限
      if (selection.length > this.maxSelected) {
        this.$message.warning(`最多可选择 ${this.maxSelected} 个方案`)
        // 还原为前 maxSelected 个
        const kept = selection.slice(0, this.maxSelected)
        this.$refs.schemeTable.clearSelection()
        this.$nextTick(() => {
          kept.forEach(row => this.$refs.schemeTable.toggleRowSelection(row, true))
          this.selectedSchemes = kept
        })
        return
      }
      this.selectedSchemes = selection
    },

    // 确认选择
    handleConfirm() {
      if (this.selectedSchemes.length === 0) {
        this.$message.warning('请选择方案')
        return
      }
      if (this.multiple) {
        const result = this.selectedSchemes.map(s => ({
          id: s.id,
          title: s.title,
          price: s.price || '0.00',
          category: s.category,
          expert_info: s.expert_info,
          pass_lx_text: s.pass_lx_text,
          show_lx_text: s.show_lx_text
        }))
        this.$emit('confirm', result)
      } else {
        const s = this.selectedSchemes[0]
        this.$emit('confirm', {
          id: s.id,
          title: s.title,
          price: s.price || '0.00',
          category: s.category,
          expert_info: s.expert_info,
          pass_lx_text: s.pass_lx_text,
          show_lx_text: s.show_lx_text
        })
      }
      this.handleClose()
    },

    // 关闭弹窗
    handleClose() {
      this.dialogVisible = false
      this.selectedSchemes = []
      this.$refs.schemeTable.clearSelection()
    }
  }
}
</script>

<style scoped>
.scheme-selector-dialog .el-dialog__body {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.scheme-info {
  display: flex;
  flex-direction: column;
}

.scheme-title {
  font-weight: 500;
  color: #303133;
  margin-bottom: 5px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-info {
  color: #606266;
  font-size: 14px;
}
</style>

